import { create } from 'zustand'

interface State {
  snippets: ISnippet[];
  searchValue: string;
  searchShortcutError: string;
  editCateId: number | null;
  managerShortcutError: string;
  activeId: string | number;
  messageGenerating: boolean;
  setSnippets: (list: ISnippet[]) => void;
  setSearchValue: (val: string) => void;
  setSearchShortcutError: (error: string) => void;
  setEditCateId: (cid: number | null) => void;
  setManagerShortcutError: (error: string) => void;
  setActiveId:
    (id: string | number | ((id: string | number) => string | number)) => void;
  setMessageGenerating: (bool: boolean) => void;
}

export const useSnippetsStore = create<State>((set) => ({
  snippets: [],
  searchValue: '',
  searchShortcutError: '',
  editCateId: null,
  managerShortcutError: '',
  activeId: 0,
  messageGenerating: false,
  setSnippets: (snippets: ISnippet[]) => {
    set({ snippets })
  },
  setSearchValue: (searchValue: string) => {
    set({ searchValue })
  },
  setSearchShortcutError: (searchShortcutError: string) => {
    set({ searchShortcutError })
  },
  setEditCateId: (editCateId: number | null) => set({ editCateId }),
  setManagerShortcutError: (managerShortcutError: string) => {
    set({ managerShortcutError })
  },
  setActiveId: (
    activeId: string | number | ((id: string | number) => string | number),
  ) => {
    if (typeof activeId === 'function') {
      set(state => ({
        activeId: activeId(state.activeId),
      }))
    } else {
      set({ activeId })
    }
  },
  setMessageGenerating: (messageGenerating: boolean) => {
    set({ messageGenerating })
  },
}))
